using System;
using Tycho.Parser.Peg;

namespace Tycho.Grammar {
    public class SequenceRuleInfixInformationBuilder : ISequenceRuleInfixInformationBuilder {
        private IRule FirstRule;
        private IRule LastRule;
        private IProduction Production;

        public void Add (IRule rule) {
            if (FirstRule == null) {
                FirstRule = rule;
                Production = rule.Production;
            } else if (rule.HasProduction && rule.Production == Production) {
                LastRule = rule;
            } else {
                LastRule = null;
            }
        }

        public IInfixInformation CreateInfixInformation () {
            if (IsInfix ()) {
                return new InfixInformation (FirstRule, LastRule, Production);
            } else {
                return new NotInfixInformation ();
            }
        }

        private bool IsInfix () {
            return HasProduction (FirstRule) && HasProduction (LastRule) && LastRule.Production == LastRule.Production;
        }

        private bool HasProduction (IRule rule) {
            return rule != null && rule.HasProduction;
        }
    }
}